package admin_menu_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/models/res"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"time"
)

type MenuRsp struct {
	ID           uint            `json:"id"`
	CreatedAt    time.Time       `json:"created_at"`
	UpdatedAt    time.Time       `json:"updated_at"`
	Title        string          `json:"title"`         // 名称
	Path         string          `json:"path"`          // 路劲
	Slogan       string          `json:"slogan"`        // slogan
	Abstract     ctype.Array     `json:"abstract"`      // 简介
	AbstractTime int             `json:"abstract_time"` // 简介的切换时间 size:6 是 smallint(6)
	ImageTime    int             `json:"image_time"`    // 菜单图片的切换时间 为0表示不切换
	Sort         int             `json:"sort"`          // 菜单的顺序
	ImageList    []Menu2ImageRsp `json:"image_list"`
}

type Menu2ImageRsp struct {
	ImageId   uint   `json:"image_id"`
	ImageName string `json:"image_name"`
	ImagePath string `json:"image_path"`
	Sort      int    `json:"sort"`
}

func (AdminMenuApi) MenuList(c *gin.Context) {
	// 查询菜单
	var menuList []models.MenuModel
	var menuIDList []uint
	global.DB.Order("sort asc").Find(&menuList).Select("id").Scan(&menuIDList)
	// 查询关联表
	var menu2ImageList []models.Menu2ImageModel
	global.DB.Preload("ImageModel").Order("sort asc").Find(&menu2ImageList, "menu_id in ?", menuIDList)
	var respList []MenuRsp
	for _, model := range menuList {
		var menu2ImageResponseList []Menu2ImageRsp
		for _, imageModel := range menu2ImageList {
			if model.ID == imageModel.MenuID {
				menu2ImageResponseList = append(menu2ImageResponseList, Menu2ImageRsp{
					ImageId:   imageModel.ImageID,
					ImageName: imageModel.ImageModel.Name,
					ImagePath: imageModel.ImageModel.Path,
					Sort:      imageModel.Sort,
				})
			}
		}
		var menu MenuRsp
		copier.Copy(&menu, &model)
		menu.ImageList = menu2ImageResponseList
		respList = append(respList, menu)
	}
	res.OkWithList(respList, int64(len(menuList)), c)
}
